import { ethers } from "ethers";
import ABI from "../abis/MyNFT.json";
import axios from "axios";
import "../const/contractAddress.js";
import { SEPOLIA_NET } from "../const/contractAddress.js";

let provider = new ethers.BrowserProvider(window.ethereum);
const contractAddress = SEPOLIA_NET.erc721;
const contract = new ethers.Contract(
  contractAddress,
  ABI,
  await provider.getSigner()
);

export async function balanceOf(address) {
  const result = await contract.balanceOf(address);
  return Number(result);
}

export async function tokenOfOwnerByIndex(owner, index) {
  const result = await contract.tokenOfOwnerByIndex(owner, index);
  return Number(result);
}

export async function tokenURI(tokenId) {
  const result = await contract.tokenURI(tokenId);
}

export async function getMetadata(tokenId) {
  const ipfsGateaway = "https://ipfs.io/ipfs/";
  const result = await contract.tokenURI(tokenId);
  const response = await axios.get(ipfsGateaway + result);

  return {
    tokenId: tokenId,
    title: response.data.title,
    description: response.data.description,
    images: response.data.image,
  };
}
export async function safeTransferFrom(address, to, tokenId) {
  const result = await contract.safeTransferFrom(address, to, tokenId);
  return result.hash;
}
